<template>
  <div class="payment-management">
    <el-card class="page-container">
      <template #header>
        <div class="card-header">
          <span>参合缴费登记</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="姓名">
            <el-input
              v-model="searchForm.insuredName"
              placeholder="请输入参合人姓名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input
              v-model="searchForm.cardId"
              placeholder="请输入身份证号"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 参合人信息表格 -->
      <el-table
        v-if="showInsuredTable"
        :data="filteredInsuredList"
        border
        style="width: 100%"
        @row-click="handleSelectInsured"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="insured_name" label="姓名" width="120" />
        <el-table-column prop="card_id" label="身份证号" width="180" />
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="address" label="地址" min-width="200" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handlePayment(scope.row)"
            >缴费</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 缴费记录表格 -->
      <div v-else class="payment-history">
        <div class="table-header">
          <h3>缴费记录</h3>
          <el-button type="primary" @click="showInsuredTable = true">返回查询</el-button>
        </div>
        <el-table :data="paymentList" border style="width: 100%">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="rural_card_no" label="参合证号" width="120" />
          <el-table-column prop="invoice_no" label="发票号" width="120" />
          <el-table-column prop="amount" label="缴费金额" width="120">
            <template #default="scope">
              {{ scope.row.amount.toFixed(2) }} 元
            </template>
          </el-table-column>
          <el-table-column prop="payment_year" label="缴费年度" width="100" />
          <el-table-column prop="payment_time" label="缴费时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.payment_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="operator_name" label="操作员" width="120" />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button
                type="success"
                size="small"
                @click="handlePrint(scope.row)"
              >打印</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 缴费对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="参合缴费"
      width="40%"
    >
      <el-form
        ref="paymentForm"
        :model="currentPayment"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="insured_name">
          <el-input v-model="currentPayment.insured_name" disabled />
        </el-form-item>
        <el-form-item label="身份证号" prop="card_id">
          <el-input v-model="currentPayment.card_id" disabled />
        </el-form-item>
        <el-form-item label="参合证号" prop="rural_card_no">
          <el-input v-model="currentPayment.rural_card_no" placeholder="请输入参合证号" />
        </el-form-item>
        <el-form-item label="发票号" prop="invoice_no">
          <el-input v-model="currentPayment.invoice_no" placeholder="请输入发票号" />
        </el-form-item>
        <el-form-item label="缴费金额" prop="amount">
          <el-input-number
            v-model="currentPayment.amount"
            :precision="2"
            :step="10"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="缴费年度" prop="payment_year">
          <el-date-picker
            v-model="currentPayment.payment_year"
            type="year"
            format="YYYY"
            value-format="YYYY"
            placeholder="选择年份"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPayment">确认缴费</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 打印预览对话框 -->
    <el-dialog
      v-model="printDialogVisible"
      title="缴费凭证打印预览"
      width="60%"
    >
      <div class="print-area" ref="printArea">
        <h2 class="print-title">参合缴费凭证</h2>
        <div class="print-content">
          <div class="print-item">
            <span class="label">参合证号：</span>
            <span>{{ printData.rural_card_no }}</span>
          </div>
          <div class="print-item">
            <span class="label">发票号：</span>
            <span>{{ printData.invoice_no }}</span>
          </div>
          <div class="print-item">
            <span class="label">姓名：</span>
            <span>{{ printData.insured_name }}</span>
          </div>
          <div class="print-item">
            <span class="label">身份证号：</span>
            <span>{{ printData.card_id }}</span>
          </div>
          <div class="print-item">
            <span class="label">缴费金额：</span>
            <span>{{ printData.amount?.toFixed(2) }} 元</span>
          </div>
          <div class="print-item">
            <span class="label">缴费年度：</span>
            <span>{{ printData.payment_year }} 年</span>
          </div>
          <div class="print-item">
            <span class="label">缴费时间：</span>
            <span>{{ formatDateTime(printData.payment_time) }}</span>
          </div>
          <div class="print-item">
            <span class="label">操作员：</span>
            <span>{{ printData.operator_name }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="printDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="doPrint">确认打印</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 模拟参合人数据
const mockInsured = [
  {
    id: 1,
    insured_name: '张三',
    card_id: '330102199001011234',
    gender: '男',
    address: '浙江省杭州市上城区某某街道1号',
    phone: '13812345678'
  },
  {
    id: 2,
    insured_name: '李四',
    card_id: '330102199202022345',
    gender: '女',
    address: '浙江省杭州市下城区某某街道2号',
    phone: '13912345678'
  }
]

// 模拟缴费记录数据
const mockPayments = [
  {
    id: 1,
    rural_card_no: 'NH202401001',
    invoice_no: 'FP202401001',
    amount: 280.00,
    payment_year: '2024',
    payment_time: '2024-01-01 09:00:00',
    operator_id: 1,
    operator_name: '王经办',
    card_id: '330102199001011234',
    insured_name: '张三'
  }
]

// 表单验证规则
const rules = {
  rural_card_no: [
    { required: true, message: '请输入参合证号', trigger: 'blur' },
    { pattern: /^NH\d{9}$/, message: '参合证号格式：NH+9位数字', trigger: 'blur' }
  ],
  invoice_no: [
    { required: true, message: '请输入发票号', trigger: 'blur' },
    { pattern: /^FP\d{9}$/, message: '发票号格式：FP+9位数字', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入缴费金额', trigger: 'blur' }
  ],
  payment_year: [
    { required: true, message: '请选择缴费年度', trigger: 'change' }
  ]
}

const insuredList = ref([])
const paymentList = ref([])
const dialogVisible = ref(false)
const printDialogVisible = ref(false)
const showInsuredTable = ref(true)
const paymentForm = ref(null)
const printArea = ref(null)

const searchForm = ref({
  insuredName: '',
  cardId: ''
})

const currentPayment = ref({
  rural_card_no: '',
  invoice_no: '',
  amount: 280.00,
  payment_year: new Date().getFullYear().toString(),
  card_id: '',
  insured_name: ''
})

const printData = ref({})

// 过滤后的参合人列表
const filteredInsuredList = computed(() => {
  const { insuredName, cardId } = searchForm.value
  return insuredList.value.filter(item => {
    const matchName = !insuredName || item.insured_name.includes(insuredName)
    const matchId = !cardId || item.card_id.includes(cardId)
    return matchName && matchId
  })
})

// 日期时间格式化
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString('zh-CN')
}

// 初始化数据
onMounted(() => {
  insuredList.value = [...mockInsured]
  paymentList.value = [...mockPayments]
})

// 处理搜索
const handleSearch = () => {
  // 实际项目中这里会调用后端API
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    insuredName: '',
    cardId: ''
  }
}

// 选择参合人
const handleSelectInsured = (row) => {
  handlePayment(row)
}

// 处理缴费
const handlePayment = (row) => {
  currentPayment.value = {
    rural_card_no: '',
    invoice_no: '',
    amount: 280.00,
    payment_year: new Date().getFullYear().toString(),
    card_id: row.card_id,
    insured_name: row.insured_name
  }
  dialogVisible.value = true
}

// 提交缴费
const submitPayment = () => {
  if (!paymentForm.value) return

  paymentForm.value.validate((valid) => {
    if (valid) {
      // 生成缴费记录
      const newPayment = {
        id: paymentList.value.length + 1,
        ...currentPayment.value,
        payment_time: new Date().toISOString(),
        operator_id: 1, // 实际应该从登录用户信息中获取
        operator_name: '王经办' // 实际应该从登录用户信息中获取
      }
      
      paymentList.value.push(newPayment)
      ElMessage.success('缴费成功')
      dialogVisible.value = false
      showInsuredTable.value = false
      
      // 打印凭证
      printData.value = newPayment
      printDialogVisible.value = true
    }
  })
}

// 处理打印
const handlePrint = (row) => {
  printData.value = row
  printDialogVisible.value = true
}

// 执行打印
const doPrint = () => {
  const content = printArea.value.innerHTML
  const printWindow = window.open('', '_blank')
  printWindow.document.write(`
    <html>
      <head>
        <title>参合缴费凭证</title>
        <style>
          .print-title { text-align: center; margin-bottom: 30px; }
          .print-content { padding: 20px; }
          .print-item { margin: 15px 0; line-height: 24px; }
          .label { font-weight: bold; margin-right: 10px; display: inline-block; width: 100px; }
        </style>
      </head>
      <body>${content}</body>
    </html>
  `)
  printWindow.document.close()
  printWindow.print()
  printDialogVisible.value = false
}
</script>

<style scoped>
.payment-management {
  padding: 20px;
}

.page-container {
  margin: 0;
  min-height: calc(100vh - 140px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header h3 {
  margin: 0;
}

.el-table {
  margin-top: 20px;
}

/* 打印样式 */
.print-title {
  text-align: center;
  margin-bottom: 30px;
}

.print-content {
  padding: 20px;
}

.print-item {
  margin: 15px 0;
  line-height: 24px;
}

.print-item .label {
  font-weight: bold;
  margin-right: 10px;
  display: inline-block;
  width: 100px;
}
</style>